import React, { useState, useEffect } from "react";
import {
  Card,
  Row,
  Col,
  Typography,
  Space,
  Badge,
  Avatar,
  List,
  Tag,
  Calendar,
  Progress,
  Statistic,
  Button,
  Empty,
} from "antd";
import {
  UserOutlined,
  BookOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  BellOutlined,
  FileTextOutlined,
  FormOutlined,
} from "@ant-design/icons";
import styled from "styled-components";
import type {
  StudentInfo,
  CourseInfo,
  HomeworkInfo,
  ExamInfo,
  Notification,
  LearningProgress,
} from "../types";

// 根据用户角色生成默认头像
const getDefaultAvatar = (name: string, role: string) => {
  // 使用姓名的hash值作为种子，避免中文编码问题
  const hash = name.split('').reduce((a, b) => {
    a = ((a << 5) - a) + b.charCodeAt(0);
    return a & a;
  }, 0);
  const seed = Math.abs(hash).toString();
  
  // 根据角色设置不同的卡通头像样式
  if (role === "teacher") {
    // 教师使用更成熟的卡通风格
    return `https://api.dicebear.com/7.x/adventurer/svg?seed=${seed}&backgroundColor=b6e3f4`;
  } else {
    // 学生使用活泼的卡通风格
    return `https://api.dicebear.com/7.x/personas/svg?seed=${seed}&backgroundColor=ffdfbf`;
  }
};

const { Title, Text } = Typography;

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  .ant-card-head-title {
    font-weight: bold;
  }
`;

interface DashboardItem {
  id: string;
  type: "exam" | "homework";
  courseId: string;
  courseName: string;
  data: ExamInfo | HomeworkInfo;
}

const StudentDashboard: React.FC = () => {
  const [studentInfo, setStudentInfo] = useState<StudentInfo>();
  const [courses, setCourses] = useState<CourseInfo[]>([]);
  const [homework, setHomework] = useState<HomeworkInfo[]>([]);
  const [exams, setExams] = useState<ExamInfo[]>([]);
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [progress, setProgress] = useState<LearningProgress>();

  useEffect(() => {
    // 生成静态真实数据
    const generateMockData = () => {
      // 学生信息
    setStudentInfo({
      id: "1",
        name: "李明华",
      studentId: "2021001",
      className: "计算机科学与技术1班",
      major: "计算机科学与技术",
      grade: "2021级",
        email: "liminghua@university.edu.cn",
        phone: "138****1234",
        avatar: getDefaultAvatar("李明华", "student")
    });

      // 课程信息
          setCourses([
      {
        id: "1",
          name: "数据结构与算法",
          teacherName: "张伟",
          semester: "2024-2025-1",
          schedule: "周一 1-2节, 周三 3-4节",
        classroom: "A301",
        credit: 4,
          description: "学习基本数据结构与算法设计"
      },
        {
          id: "2",
          name: "数据库系统原理",
          teacherName: "李雅琴",
          semester: "2024-2025-1",
          schedule: "周二 1-2节, 周四 3-4节",
          classroom: "B205",
          credit: 3,
          description: "数据库设计与SQL编程"
        },
        {
          id: "3",
          name: "计算机网络",
          teacherName: "王建国",
          semester: "2024-2025-1",
          schedule: "周五 1-2节",
          classroom: "C401",
          credit: 3,
          description: "网络协议与网络编程"
        },
        {
          id: "4",
          name: "软件工程",
          teacherName: "刘梦华",
          semester: "2024-2025-1",
          schedule: "周三 5-6节",
          classroom: "D102",
          credit: 2,
          description: "软件开发流程与方法"
        }
    ]);

      // 作业信息
    setHomework([
      {
        id: "1",
          title: "链表实现与操作",
        courseId: "1",
          deadline: "2024-12-25 23:59:59",
          description: "实现单链表、双链表的基本操作，包括插入、删除、查找等功能",
        status: "pending",
          attachments: [
            { name: "作业要求.pdf", url: "#" },
            { name: "参考代码.zip", url: "#" }
          ]
        },
        {
          id: "2",
          title: "数据库设计报告",
          courseId: "2",
          deadline: "2024-12-28 23:59:59",
          description: "设计一个学生信息管理系统数据库，包含ER图和SQL语句",
          status: "submitted",
          score: 92,
          feedback: "设计思路清晰，SQL语句规范，建议优化索引设计"
        },
        {
          id: "3",
          title: "网络协议分析",
          courseId: "3",
          deadline: "2024-12-30 23:59:59",
          description: "使用Wireshark分析HTTP协议数据包",
          status: "graded",
          score: 88,
          feedback: "分析详细，但缺少对HTTPS协议的分析"
        }
      ]);

      // 考试信息
    setExams([
      {
        id: "1",
          name: "数据结构期中考试",
        courseId: "1",
          startTime: "2024-12-26 14:00:00",
          endTime: "2024-12-26 16:00:00",
          duration: 120,
          totalScore: 100,
          status: "upcoming"
        },
        {
          id: "2",
          name: "数据库系统期末考试",
          courseId: "2",
          startTime: "2025-01-15 09:00:00",
          endTime: "2025-01-15 11:00:00",
        duration: 120,
        totalScore: 100,
          status: "upcoming"
      },
        {
          id: "3",
          name: "计算机网络期中考试",
          courseId: "3",
          startTime: "2024-12-20 14:00:00",
          endTime: "2024-12-20 15:30:00",
          duration: 90,
          totalScore: 100,
          status: "completed",
          score: 85,
          rank: 12
        }
    ]);

      // 通知信息
    setNotifications([
      {
        id: "1",
          title: "新作业发布通知",
          content: "数据结构与算法课程发布了新的作业：链表实现与操作",
        type: "homework",
          time: "2024-12-20 10:30:00",
          read: false,
          link: "/homework/1"
        },
        {
          id: "2",
          title: "考试安排通知",
          content: "数据结构期中考试将于12月26日14:00-16:00在A301教室进行",
          type: "exam",
          time: "2024-12-19 15:20:00",
        read: false,
          link: "/exams/1"
      },
        {
          id: "3",
          title: "课程调整通知",
          content: "软件工程课程本周三调整为线上授课，请及时关注",
          type: "course",
          time: "2024-12-18 09:15:00",
          read: true,
          link: "/courses/4"
        },
        {
          id: "4",
          title: "系统维护通知",
          content: "系统将于今晚22:00-24:00进行维护，期间可能无法访问",
          type: "system",
          time: "2024-12-17 16:45:00",
          read: true,
          link: "#"
        }
    ]);

      // 学习进度
    setProgress({
      courseId: "1",
      attendance: {
        total: 32,
        present: 30,
        late: 1,
        absent: 1,
      },
      homework: {
          total: 12,
          submitted: 10,
          graded: 9,
          averageScore: 87,
      },
      exams: {
          total: 3,
        completed: 1,
          averageScore: 85,
          ranking: 12,
      },
      knowledgePoints: {
          "线性表": {
            mastery: 90,
            recentTrend: [75, 80, 90],
            needsImprovement: false,
          },
          "栈与队列": {
          mastery: 85,
          recentTrend: [70, 75, 85],
          needsImprovement: false,
        },
          "树结构": {
          mastery: 75,
            recentTrend: [60, 65, 75],
            needsImprovement: true,
          },
          "图算法": {
            mastery: 65,
            recentTrend: [50, 55, 65],
          needsImprovement: true,
        },
      },
    });
    };

    generateMockData();
  }, []);



  const mockItems: DashboardItem[] = [
    {
      id: "1",
      type: "exam",
      courseId: "1",
      courseName: "数据结构与算法",
      data: {
        id: "e1",
        name: "数据结构期中考试",
        courseId: "1",
        startTime: "2024-12-26 14:00",
        endTime: "2024-12-26 16:00",
        duration: 120,
        totalScore: 100,
        status: "upcoming",
      },
    },
    {
      id: "2",
      type: "homework",
      courseId: "1",
      courseName: "数据结构与算法",
      data: {
        id: "h1",
        title: "链表实现与操作",
        courseId: "1",
        deadline: "2024-12-25 23:59:59",
        description: "实现单链表、双链表的基本操作，包括插入、删除、查找等功能",
        status: "pending",
      },
    },
    {
      id: "3",
      type: "homework",
      courseId: "2",
      courseName: "数据库系统原理",
      data: {
        id: "h2",
        title: "数据库设计报告",
        courseId: "2",
        deadline: "2024-12-28 23:59:59",
        description: "设计一个学生信息管理系统数据库，包含ER图和SQL语句",
        status: "submitted",
      },
    },
    {
      id: "4",
      type: "exam",
      courseId: "2",
      courseName: "数据库系统原理",
      data: {
        id: "e2",
        name: "数据库系统期末考试",
        courseId: "2",
        startTime: "2025-01-15 09:00",
        endTime: "2025-01-15 11:00",
        duration: 120,
        totalScore: 100,
        status: "upcoming",
      },
    },
  ];

  const getItemTitle = (item: DashboardItem) => {
    if (item.type === "exam") {
      return (item.data as ExamInfo).name;
    }
    return (item.data as HomeworkInfo).title;
  };

  const getItemIcon = (type: DashboardItem["type"]) => {
    switch (type) {
      case "exam":
        return <BookOutlined />;
      case "homework":
        return <FormOutlined />;
      default:
        return null;
    }
  };

  return (
    <div style={{ padding: "24px" }}>
      {/* 个人信息卡片 */}
      <StyledCard>
        <Row gutter={24} align="middle">
          <Col>
            <Avatar size={64} icon={<UserOutlined />} />
          </Col>
          <Col>
            <Space direction="vertical">
              <Title level={4}>{studentInfo?.name}</Title>
              <Space>
                <Text type="secondary">学号：{studentInfo?.studentId}</Text>
                <Text type="secondary">班级：{studentInfo?.className}</Text>
                <Text type="secondary">专业：{studentInfo?.major}</Text>
              </Space>
            </Space>
          </Col>
        </Row>
      </StyledCard>

      <Row gutter={24}>
        <Col span={16}>
          {/* 待办事项 */}
          <StyledCard
            title={
              <Space>
                <ClockCircleOutlined />
                <span>待办事项</span>
              </Space>
            }
          >
            <List
              itemLayout="horizontal"
              dataSource={mockItems}
              renderItem={(item) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={getItemIcon(item.type)}
                    title={getItemTitle(item)}
                    description={
                      <Space>
                        <Tag color={item.type === "homework" ? "blue" : "red"}>
                          {item.type === "homework" ? "作业" : "考试"}
                        </Tag>
                        <span>
                          <ClockCircleOutlined />{" "}
                          {item.type === "homework"
                            ? `截止日期：${(item.data as HomeworkInfo).deadline}`
                            : `考试时间：${(item.data as ExamInfo).startTime}`}
                        </span>
                      </Space>
                    }
                  />
                </List.Item>
              )}
            />
          </StyledCard>

          {/* 学习进度 */}
          <StyledCard
            title={
              <Space>
                <CheckCircleOutlined />
                <span>学习进度</span>
              </Space>
            }
          >
            <Row gutter={[24, 24]}>
              <Col span={8}>
                <Statistic
                  title="出勤率"
                  value={
                    ((progress?.attendance.present || 0) /
                      (progress?.attendance.total || 1)) *
                    100
                  }
                  suffix="%"
                  precision={1}
                />
                <Progress
                  percent={
                    ((progress?.attendance.present || 0) /
                      (progress?.attendance.total || 1)) *
                    100
                  }
                  status="active"
                />
              </Col>
              <Col span={8}>
                <Statistic
                  title="作业完成率"
                  value={
                    ((progress?.homework.submitted || 0) /
                      (progress?.homework.total || 1)) *
                    100
                  }
                  suffix="%"
                  precision={1}
                />
                <Progress
                  percent={
                    ((progress?.homework.submitted || 0) /
                      (progress?.homework.total || 1)) *
                    100
                  }
                  status="active"
                />
              </Col>
              <Col span={8}>
                <Statistic
                  title="平均成绩"
                  value={progress?.homework.averageScore || 0}
                  suffix="/100"
                />
                <Progress
                  percent={progress?.homework.averageScore || 0}
                  status="active"
                />
              </Col>
            </Row>
          </StyledCard>
        </Col>

        <Col span={8}>
          {/* 课程表 */}
          <StyledCard
            title={
              <Space>
                <BookOutlined />
                <span>课程表</span>
              </Space>
            }
          >
            <Calendar fullscreen={false} />
          </StyledCard>

          {/* 通知公告 */}
          <StyledCard
            title={
              <Space>
                <BellOutlined />
                <span>通知公告</span>
              </Space>
            }
          >
            <List
              dataSource={notifications}
              renderItem={(item) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={
                      <Badge dot={!item.read}>
                        <Avatar icon={<BellOutlined />} />
                      </Badge>
                    }
                    title={item.title}
                    description={
                      <Space>
                        <Tag
                          color={item.type === "homework" ? "blue" : "green"}
                        >
                          {item.type}
                        </Tag>
                        <Text type="secondary">
                          {item.time.substring(0, 16)}
                        </Text>
                      </Space>
                    }
                  />
                </List.Item>
              )}
            />
          </StyledCard>
        </Col>
      </Row>
    </div>
  );
};

export default StudentDashboard;
